package com.oglvip.business.remote.support.proxy;

import com.oglvip.business.remote.support.exception.RestException;
import com.oglvip.business.remote.support.proxy.exchange.Exchanger;
import com.oglvip.business.remote.support.request.RequestEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Arrays;


/**
 * 请求代理
 */
public class RestProxyHandler implements InvocationHandler {

//	private final static 

    private final static Logger logger_ = LoggerFactory.getLogger(RestProxyHandler.class);

    // 要代理的原始对象
    private Object objOriginal;

    private Exchanger exchanger;

    //实际处理的类

    /**
     * 构造函数。
     *
     * @param obj 要代理的原始对象。
     */
    public RestProxyHandler(Object obj,Exchanger exchanger) {
        this.objOriginal = obj;
        this.exchanger = exchanger;
    }

    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        //Object继承的方法
        if (method.getDeclaringClass() == Object.class) {
            return method.invoke(objOriginal, args);
        }

        if (objOriginal == null) {
            logger_.error("objOriginal is not proxied " + proxy);
            return null;
        }
        if (objOriginal.getClass().getInterfaces().length != 1) {
            logger_.error("wrong extends " + Arrays.toString(objOriginal.getClass().getInterfaces()));
            return null;
        }

        RequestEntity request = RequestBuilder.build(objOriginal.getClass(), method, args);

        Object result = null;
        try {
            result = exchanger.request(request,method);
        } catch (RestException e) {
            e.printStackTrace();
            throw new RestException("cant handle method "+method.getName());
        }

        return result;

    }

}
